package icu.sehnen.utils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
@WebServlet("/code")
public class Code extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        创建空白图片
        BufferedImage image=new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
//        画笔
        Graphics g=image.getGraphics();
        Random random=new Random();
        g.setColor(new Color(255,255,255));
//   绘制矩形背景
        g.fillRect(0,0,100,40);
//        长度为5的字符串
        String number=getNumber(4);
        req.getSession().setAttribute("code",number);
        g.setColor(new Color(0,0,0));
        g.setFont(new Font("宋体",Font.BOLD,28));
//        绘制字符串
        g.drawString(number,5,25);
        for (int i=0;i<15;i++){
            g.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
            g.drawLine(random.nextInt(100),random.nextInt(30),random.nextInt(100),random.nextInt(100));
        }
        resp.setContentType("image/jpeg");
        OutputStream ops=resp.getOutputStream();
        ImageIO.write(image,"jpeg",ops);
        ops.close();

    }

    private String getNumber(int size) {
        String str="asdfghjkqwertyuiopzxcvbnm";
        StringBuilder number=new StringBuilder();
        Random r=new Random();
        for (int i=0;i<size;i++){
            int index=r.nextInt(str.length());
            number.append(str.charAt(index));
        }
        return number.toString();

    }

}
